package com.li.ws;


import com.li.pojo.Message;
import com.li.pojo.User;
import com.li.util.MessageUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chat/{uid}")
@Component
public class ChatEndpoint {
    //每一个客户端对应一个ChatEndpoint对象

    //用来存储每一个客户端对象对应的Session对象,并发编程用到的Map实现类，线程安全ConcurrentHashMap
    private static Map<String,Set<Session>> allOnlineUser = new ConcurrentHashMap<>();

    //session对象 通过该对象可以发送消息给指定的用户

    private Set<Session> userAllClient;

    private String uid;
    //声明HttpSession对象 可以取出之前存储再httpSession对象中的值
//    private HttpSession httpSession;

    //建立连接时调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value="uid")String uid){
        System.out.println(uid+"上线了");
        //将用户添加到所有用户列表
        this.uid = uid;
        this.userAllClient= allOnlineUser.get(uid);
        if (CollectionUtils.isEmpty(userAllClient)){
            this.userAllClient = new HashSet<>();
            allOnlineUser.put(uid,userAllClient);
        }
        this.userAllClient.add(session);

        broad(MessageUtils.getMessage("1",this.uid,"all",allOnlineUser.keySet(),"addUser"));


//        //将局部的session对象赋值给成员session
//        this.session=session;
//        //获取httpSession对象
//        this.httpSession =(HttpSession)config.getUserProperties().get(HttpSession.class.getName());
//
//        //将当前登录对象存储到容器中
//        onlineUser.put((String) httpSession.getAttribute("username"),this);
//
//        //将当前在线用户的所有用户名推送给所有用户名
//        //获取消息对象
//        String msg = MessageUtils.getMessage(true,null,onlineUser.keySet());
//        //调用方法进行系统推送
//        this.broadcastAllUsers(msg);
    }
    //接受客户端发送的数据时被调用
    @OnMessage
    public void onMessage(String msg,Session session){

        Message message = MessageUtils.getMessage(msg);
        String event = message.getEvent();

        if (event==null){
            System.out.println("收到消息,事假为:"+event);
            message.setEvent("broad");
            message.setTo(uid);
            broad(MessageUtils.getMessage(message));
        }else if ("oneMessage".equals(event)){
            System.out.println("收到消息,事假为:"+event);
            sendMessage(message);
        }



//        try {
//            System.out.println("收到："+msg);
//            session.getBasicRemote().sendText(msg);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        try{
//            //将msg转换为message对象
//            ObjectMapper mapper = new ObjectMapper();
//            Message message = mapper.readValue(msg, Message.class);
//            //获取接收消息的用户
//            String toName = message.getToName();
//            //获取消息数据
//            String data = message.getMessage();
//            //获取当前登录的用户
//            String username = (String)httpSession.getAttribute("username");
//            //获取推送给指定用户的消息格式数据
//            String resultMessage = MessageUtils.getMessage(false,username,data);
//            //发送数据
//            onlineUser.get("toName").session.getBasicRemote().sendText(msg);
//            //
//
//        } catch (Exception e){
//            e.printStackTrace();
//        }

    }
    //连接关闭时被调用
    @OnClose
    public void onClose(Session session){
        //删除离线用户
        System.out.println(uid+"离线了");
        userAllClient.remove(session);
        if (CollectionUtils.isEmpty(userAllClient)){
            allOnlineUser.remove(this.uid);
        }
//        String username = (String) httpSession.getAttribute("username");
//        onlineUser.remove(username);

        //广播通知
//        String msg = MessageUtils.getMessage(true,null,onlineUser.keySet());
//        broadcastAllUsers(msg);

        broad(MessageUtils.getMessage("1",this.uid,"all",allOnlineUser.keySet(),"deleteUser"));
    }

    private void broad(String msg){
//        //要将该消息推送给所有的客户端
//        Set<String> names = onlineUser.keySet();
//        for (String name:names){
//            ChatEndpoint chatEndpoint = onlineUser.get(name);
//            try {
//                chatEndpoint.session.getBasicRemote().sendText(msg);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        Set<String> usersSet = allOnlineUser.keySet();
        for(String userSet:usersSet){
            Set<Session>sessions = allOnlineUser.get(userSet);
            for (Session session:sessions){
                try {
                    session.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
    private void sendMessage(Message message){
        if (!"1".equals(message.getIsGroup())){

            String to = (String) message.getTo();
            Set<Session> toUsers = allOnlineUser.get(to);
            for (Session toUser:toUsers){
                try {
                    toUser.getBasicRemote().sendText(MessageUtils.getMessage(message));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
